package com.lock;

import java.util.concurrent.locks.ReentrantLock;

/**
 * ReentrantLock的使用
 * 优点； 可以重入锁 、 中断锁、 可限时（lock.tryLock(3, SECOND)） 、公平锁（性能比较差，先到先得）
 */
public class ReentrantLockTest extends Thread{

    /**
     * 创建锁对象
     */
    public static ReentrantLock lock = new ReentrantLock();
    public static int i = 0;

    public ReentrantLockTest(String name) {
        super.setName(name);
    }

    @Override
    public void run() {
        for (int j = 0; j < 100000; j++) {
            //加锁
            lock.lock();
            try {
                System.out.println(this.getName() + " " + i);
                i++;
            } finally {
                //解锁
                lock.unlock();
            }
        }
    }

    public static void main(String[] args) throws InterruptedException { //有中断异常
        ReentrantLockTest test1 = new ReentrantLockTest("thread1");
        ReentrantLockTest test2 = new ReentrantLockTest("thread2");

        test1.start();
        test2.start();
        test1.join();
        test2.join();
        System.out.println(i); //如果没有加锁，线程数量将小于定义的大小
    }
}
